package com.md24housecall.fibromyalgiadiagnostic;

import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;

import com.google.android.gms.auth.GoogleAuthUtil;
import com.md24housecall.fibromyalgiadiagnostic.LoadingTask.LoadingTaskFinishedListener;

public class InitActivity extends Activity implements LoadingTaskFinishedListener {
	String email;
	@Override
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_init);
		AccountManager mAccountManager = AccountManager.get(this);
	    Account[] accounts = mAccountManager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
	    String[] emails = new String[accounts.length];
	    for (int i = 0; i < emails.length; i++) {
	    	emails[i] = accounts[i].name;
	    }
	    
	    TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
	    String number = tm.getLine1Number();

	    String name = null;
	    if (emails[0] != null) {
            String accountName = emails[0];
            ContentResolver cr = this.getContentResolver();
            Cursor emailCur = cr.query(
                    ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Email.DATA + " = ?",
                    new String[] { accountName }, null);
            
           
            
            while (emailCur.moveToNext()) {
            	name = emailCur
                    .getString(emailCur
                            .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            }
            
            emailCur.close();
	    }
	    
	    
	    String params = "create_user/email/"+emails[0]+"/phone/"+number+"/user_name/"+name;
	    email = emails[0];
        new LoadingTask(this, this).execute(params); 

	    
	    
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
    public void onTaskFinished() {
        completeSplash();
    }
 
    private void completeSplash(){
        startApp();
        finish(); // Don't forget to finish this Splash Activity so the user can't return to it!
    }
 
    private void startApp() {
        Intent intent = new Intent(InitActivity.this, MainActivity.class);
        intent.putExtra("email", email);
        startActivity(intent);
    }

}
